package org.chen.hotel.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.chen.common.export.resquest.ExportRequest;
import org.chen.common.hotel.Hotel;
import org.chen.hotel.mapper.HotelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ExcelHotelExportService {

    @Autowired
    private HotelMapper hotelMapper;

    public byte[] exportHotelsToExcel(ExportRequest request) {
        try {
            List<Hotel> hotels = new ArrayList<>();

            // 根据导出类型获取数据
            for (int page = request.getStartPage(); page <= request.getEndPage(); page++) {

                // 从数据库获取对应的酒店数据
                QueryWrapper<Hotel> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("check_in_date", request.getCheckInDate())
                        .eq("check_out_date", request.getCheckOutDate())
                        .eq("room_quantity", request.getRoomQuantity())
                        .orderByDesc("create_time");

                if (request.getKeyword() != null && !request.getKeyword().trim().isEmpty()) {
                    queryWrapper.like("search_keywords", request.getKeyword());
                }

                // 分页查询
                int offset = (page - 1) * request.getPageSize();
                queryWrapper.last("LIMIT " + offset + ", " + request.getPageSize());

                List<Hotel> pageHotels = hotelMapper.selectList(queryWrapper);
                hotels.addAll(pageHotels);
            }

            return generateExcelFile(hotels);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }

    private byte[] generateExcelFile(List<Hotel> hotels) throws Exception {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("酒店数据");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {
                "酒店名称", "英文名称", "星级", "地址", "位置描述", "城市",
                "评分", "评论数", "房型", "床型", "价格", "原价", "入住日期", "退房日期"
        };

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据
        for (int i = 0; i < hotels.size(); i++) {
            Row row = sheet.createRow(i + 1);
            Hotel hotel = hotels.get(i);

            row.createCell(0).setCellValue(hotel.getHotelName());
            row.createCell(1).setCellValue(hotel.getHotelNameEn());
            row.createCell(2).setCellValue(hotel.getHotelStar() != null ? hotel.getHotelStar() : 0);
            row.createCell(3).setCellValue(hotel.getAddress());
            row.createCell(4).setCellValue(hotel.getPositionDesc());
            row.createCell(5).setCellValue(hotel.getCityName());
            row.createCell(6).setCellValue(hotel.getCommentScore());
            row.createCell(7).setCellValue(hotel.getCommenterNumber());
            row.createCell(8).setCellValue(hotel.getRoomName());
            row.createCell(9).setCellValue(hotel.getBedInfo());
            row.createCell(10).setCellValue(hotel.getPrice() != null ? hotel.getPrice().doubleValue() : 0);
            row.createCell(11).setCellValue(hotel.getDeletePrice() != null ? hotel.getDeletePrice().doubleValue() : 0);
            row.createCell(12).setCellValue(hotel.getCheckInDate());
            row.createCell(13).setCellValue(hotel.getCheckOutDate());
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();

        return outputStream.toByteArray();
    }
}
